package com.lyz.collectionDemo.arrayList;

import java.util.ArrayList;
import java.util.Scanner;

/**
 * @ClassName ArrayListDemo4
 * @Description 元素搜索
 * @Author 2214361854
 * @Date 2022/2/16 23:24
 * @Version 1.0
 */
public class ArrayListDemo4 {
    public static void main(String[] args) {
        //创建ArrayList,泛型 Student(自定义类)
        ArrayList<Student> students = new ArrayList<Student>(){{
            add(new Student(20200321,"小明",18,"一班"));
            add(new Student(20200322,"小王",20,"二班"));
            add(new Student(20200323,"小星",20,"三班"));
            add(new Student(20200324,"小强",19,"一班"));
        }};
        System.out.println(students);
        tolist(students);
        System.out.println("=========");
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入学号(000 退出)：");
        int id = scanner.nextInt();
        Student studentByID = getStudentByID(students, id);
        while (true) {
            if (id==000) {
                System.out.println("退出系统");
                break;
            }
            if (studentByID==null) {
                System.out.println("查无此人");
            } else {
                System.out.println(studentByID.toString());
            }
        }
    }

    /**
     * 遍历Arraylist
     * @param students
     */
    public static void tolist(ArrayList<Student> students){
        for (int i = 0; i < students.size(); i++) {
            Student student = students.get(i);
            System.out.println(student.toString());
        }
    }

    /**
     * 根据学号，找学生对象并返回
     * @param students
     * @param id
     * @return
     */
    public static Student getStudentByID(ArrayList<Student> students,int id){
        for (int i = 0; i < students.size(); i++) {
            Student s = students.get(i);
            if(s.getId()==id){
                return s;
            }
        }
        return null;
    }

}
